package com.atguigu.flink.watermark;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.TimerService;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 *
 *  上游SubTask如果需要把数据发送到多个下游的SubTask，那么会对水印进行广播下游会取上游所有水印中的最小的那个作为水印
 s1,400,1
 s1,500,2
 s1,200,3
 s1,600,4
 s1,700,5
 s1,800,6
 s1,900,7
 */
public class Demo4_WaterMarkMultiParilisim
{
    public static void main(String[] args) {

       Configuration conf = new Configuration();
       conf.setInteger("rest.port", 3333);
       StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);


        env.getConfig().setAutoWatermarkInterval(2000);

        env.setParallelism(2);

        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy.<WaterSensor>forMonotonousTimestamps()
            .withTimestampAssigner( (e, r) -> e.getTs());

        env
            .socketTextStream("hadoop103", 8888)
            .map(new WaterSensorMapFunction())
            .assignTimestampsAndWatermarks(watermarkStrategy)
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, WaterSensor>()
            {
                @Override
                public void processElement(WaterSensor value, Context ctx, Collector<WaterSensor> out) throws Exception {
                    //时间服务  1.获取水印  2.注册定时器
                    TimerService timerService = ctx.timerService();

                    // currentWatermark: 数据达到时，算子的当前时钟
                    System.out.println("当前数据达到时，这个算子的水印(时钟)"+timerService.currentWatermark());
                    out.collect(value);
                }
            })
            .print();


                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

    }
}
